package com.utils.rsa;

import org.springframework.util.StreamUtils;

import java.io.*;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.HashMap;

public class FileUtils {
    public static void main(String[] args) throws IOException, GeneralSecurityException {
        File file = new File("C:\\Users\\dbgs\\Pictures\\啊.jpg");
        File file1 = new File("C:\\Users\\dbgs\\Pictures\\啊1.jpg");
        if (file1.exists()) {
            file1.delete();
        }
        BufferedInputStream inputStream = null;
        FileOutputStream outputStream = null;
        HashMap<String, Key> keyPair = RSAUtils.genKeyPair();
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = new FileOutputStream(file1);
            byte[] bytes = new byte[64];
            if (inputStream.read(bytes) != -1) {
                byte[] encryptByPublicKey = RSAUtils.encryptByPublicKey(RSAUtils.getPublicKey(keyPair), bytes);
                System.out.println(encryptByPublicKey.length);
//                byte[] sha256Bytes = SHA256Utils.getSHA256Bytes(encryptByPublicKey);
//                outputStream.write(sha256Bytes);
                outputStream.write(encryptByPublicKey);
            }
            StreamUtils.copy(inputStream, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }

        File file2 = new File("C:\\Users\\dbgs\\Pictures\\啊2.jpg");
        if (file2.exists()) {
            file2.delete();
        }

//        BufferedInputStream inputStream = null;
//        FileOutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file1));
            outputStream = new FileOutputStream(file2);
            byte[] bytes = new byte[128];
            if (inputStream.read(bytes) != -1) {
                byte[] decryptByPrivateKey = RSAUtils.decryptByPrivateKey(RSAUtils.getPrivateKey(keyPair), bytes);
                System.out.println(decryptByPrivateKey.length);
//                byte[] sha256Bytes = SHA256Utils.getSHA256Bytes(encryptByPublicKey);
                outputStream.write(decryptByPrivateKey);
            }
            StreamUtils.copy(inputStream, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}
